
//****************************************************************************************

#include <time.h>
#include <sys/time.h>



/**
 * ts2ns - Convert timespec values to a nanosecond value
 */
#define NS_TICKS		((long long unsigned)1000 * 1000 * 1000)

static long long unsigned ts2ns(struct timespec *ts)
{
	return ((ts->tv_sec) * NS_TICKS) + (ts->tv_nsec);
}

/**
 * ts2ns - Convert timeval values to a nanosecond value
 */
static long long unsigned tv2ns(struct timeval *tp)
{
	return ((tp->tv_sec)* NS_TICKS) + ((tp->tv_usec) * ((long long unsigned)1000));
}


/**
 * gettime - Returns current time, nano seconds:
 */
long long unsigned gettime_ns(void)
{
	static int use_clock_gettime = -1;		// Which clock to use

	if (use_clock_gettime < 0) {
		use_clock_gettime = clock_getres(CLOCK_MONOTONIC, NULL) == 0;
		if (use_clock_gettime) {
			struct timespec ts;
			ts.tv_sec = 0;
			ts.tv_nsec = 0;
			clock_settime(CLOCK_MONOTONIC, &ts);
		}
	}

	if (use_clock_gettime) {
		struct timespec ts;
		clock_gettime(CLOCK_MONOTONIC, &ts);
		return ts2ns(&ts);
	}else {
		struct timeval tp;
		gettimeofday(&tp, NULL);
		return tv2ns(&tp);
	}
}


//*****************************************************************************************



